<template>
    <el-dialog title="上传文件" :visible.sync="visible" width="410px" center>
        <el-upload ref="uploadRef" class="upload-demo" drag :action="uploadAction" :multiple="false" :headers="uploadHeader" :file-list="fileList"
            :auto-upload="false" :on-success="onUploadSuccess" :on-change="onUploadChange">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
        <span slot="footer" class="dialog-footer">
            <el-button @click="closeView">取 消</el-button>
            <el-button type="primary" @click="submitUpload">确 定</el-button>
        </span>
    </el-dialog>
</template>

<script>
import {
    getToken
} from '@/utils/auth';

export default {
    name: "UploadFiles",
    data() {
        let header = {};
        header["X-Token"] = getToken();

        return {
            visible: false,
            fileList: [],
            uploadAction: process.env.VUE_APP_BASE_API + "/api/task.upload/create",
            uploadHeader: header,
        }
    },
    methods: {
        showView() {
            this.visible = true;
            // 初始化文件列表
            this.$nextTick(() => {
                this.fileList = [];
                this.$refs.uploadRef.clearFiles();
            });
        },
        closeView() {
            this.visible = false;
        },
        onUploadSuccess(response, file, fileList) {
            if (response.code !== 200) {
                this.$message.error(response.msg);
                return;
            } else {
                this.$message.success("上传成功");
                this.$emit("success");
                this.closeView();
            };
            this.closeView();
        },
        onUploadChange(file, fileList) {
            this.fileList = fileList;
        },
        submitUpload() {
            // 如果没有选择文件，则不提交
            if (this.$refs.uploadRef.fileList.length === 0) {
                this.$message.error("请选择文件");
                return;
            }
            this.$refs.uploadRef.submit();
        },
    },
};
</script>

<style lang="less" scoped>
.form-item-row {
    margin-bottom: 12px;

    .image-group {
        // grid 布局，5列2行，第二行没有的时候不显示
        display: grid;
        grid-template-columns: repeat(10, 1fr);
        grid-gap: 10px;

        .image-box {
            width: 80px;
            height: 80px;
            border-radius: 4px;
            border: 1px solid #dedede;
            position: relative;

            .el-image {
                width: 100%;
                height: 100%;
            }

            .remove {
                display: none;
                position: absolute;
                top: 10px;
                right: 10px;
            }

            &:hover {
                .remove {
                    display: block;
                }
            }
        }

    }
}

.form-item-row:last-child {
    margin-bottom: 0;
}

.ml10 {
    margin-left: 10px;
}
</style>
